//
//  RAPOAuthViewController.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 12/29/15.
//  Copyright © 2015 RendezvousAuParadis. All rights reserved.
//

import UIKit
import SVProgressHUD

/* app key */
let kRAPAppKey = "145682325"
/* app secret */
let kRAPAppSecret = "ad4704da32dc2ca59b81bf344aa4967b"
/* redirect_uri */
let kRAPRedirectURI = "http://www.jianshu.com/"
/** 账户 */
let kRAPMyAccount = "groove.bounce@gmail.com";
//let kRAPMyAccount = "457754314@qq.com";
/** 密码 */
let kRAPMyPwd = "my1986626sina";
//let kRAPMyPwd = "xzy718728736";

//App Key：145682325
//App Secret：ad4704da32dc2ca59b81bf344aa4967b
//http://http://www.jianshu.com/users/fc23ad04f4a1/latest_articles/

//client_id	true	string	申请应用时分配的AppKey。
//redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
// https://api.weibo.com/oauth2/authorize

// 返回示例：http://www.jianshu.com/?code=4cb466b895f57e7fbed37c39540e2796

class RAPOAuthViewController: UIViewController, UIWebViewDelegate {
    
    // MARK: - 懒加载方法
    lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        self.webView = webView
        return webView
        }()
    
    // MARK: - 系统方法
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.loadRequest(NSURLRequest(URL: NSURL(string: "\(kAPI_oauth2_authorize)?client_id=\(kRAPAppKey)&redirect_uri=\(kRAPRedirectURI)")!))

        // 设置导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", target: self, action: "exitButtonClicked:")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillButtonClicked:")

    }
    
    // MARK: - 动作方法
    func exitButtonClicked(sender: UIBarButtonItem) {
        RAPLog("退出登录页面")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func autoFillButtonClicked(sender: UIBarButtonItem) {
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='\(kRAPMyAccount)';document.getElementById('passwd').value='\(kRAPMyPwd)';")
    }
    
}

//client_id	true	string	申请应用时分配的AppKey。
//client_secret	true	string	申请应用时分配的AppSecret。
//grant_type	true	string	请求的类型，填写authorization_code
//
//grant_type为authorization_code时
//code	true	string	调用authorize获得的code值。
//redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。

// MARK: - <UIWebViewDelegate>
extension RAPOAuthViewController {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let query = request.URL?.query {
            if query.hasPrefix("code=") {
                RAPLog("这是回调")
                SVProgressHUD.dismiss()
                // 截取code
                let code = query.substringFromIndex("code=".endIndex)
                
                // 将code 交给 view model
                RAPAccountViewModel.sharedViewModel.beginOauthValidationByCode(code, completion: {
                    [unowned weakSelf = self]
                    (isSuccess) -> () in
                    if isSuccess == true {
                        weakSelf.dismissViewControllerAnimated(false , completion: { () -> Void in
                            // 发送通知，切换根控制器
                            NSNotificationCenter.defaultCenter().postNotificationName(RAPEnterWelcomePageNotification, object: nil)
                        })
                        
                    } else {
                        RAPLog("数据请求失败")
                    }
                })
                return false
            }
        }
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
